package com.pengpeng.flash.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 定制一个全局的异常处理器
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * SQLIntegrityConstraintViolationException的异常处理器
     * 新增数据库数据时，因某个字段是唯一的，当新增数据重复时，报SQLIntegrityConstraintViolationException
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //判断当前异常消息中是否包含“重复条目”
        if (ex.getMessage().contains("Duplicate entry")){
            //若包含，则把重复的数据，比如username取出，返回给页面
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 捕获自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        return R.error(ex.getMessage());
    }
}
